package com.property.demo.controller;

import com.property.demo.dto.ApiResponse;
import com.property.demo.dto.MailboxDTO;
import com.property.demo.model.Mailbox;
import com.property.demo.service.MailboxService;
import com.property.demo.util.DTOMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@CrossOrigin(origins = {"http://localhost:3001", "http://localhost:8173", "http://localhost:5173", "http://localhost:3000", "http://127.0.0.1:3000", "http://127.0.0.1:5173"}, 
             allowedHeaders = {"Authorization", "Content-Type", "X-Requested-With", "Accept", "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"},
             allowCredentials = "true")
@RequestMapping("/api/mailboxes")
public class MailboxController {

    @Autowired
    private MailboxService mailboxService;

    // 获取所有信箱（分页）
    @GetMapping
    public ResponseEntity<?> getAllMailboxes(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long ownerId,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type) {
        
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
            
            Page<Mailbox> mailboxesPage;
            if (ownerId != null || (title != null && !title.isEmpty()) || 
                (status != null && !status.isEmpty()) || (type != null && !type.isEmpty())) {
                mailboxesPage = mailboxService.findByFilters(ownerId, title, status, type, pageable);
            } else {
                mailboxesPage = mailboxService.findAll(pageable);
            }
            
            List<MailboxDTO> mailboxDTOs = mailboxesPage.getContent().stream()
                    .map(DTOMapper::toMailboxDTO)
                    .collect(Collectors.toList());
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", mailboxDTOs);
            response.put("currentPage", mailboxesPage.getNumber());
            response.put("totalItems", mailboxesPage.getTotalElements());
            response.put("totalPages", mailboxesPage.getTotalPages());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 获取所有信箱（不分页）
    @GetMapping("/all")
    public ResponseEntity<?> getAllMailboxesNoPage() {
        try {
            List<Mailbox> mailboxes = mailboxService.findAll();
            List<MailboxDTO> mailboxDTOs = DTOMapper.toMailboxDTOList(mailboxes);
            return ResponseEntity.ok(mailboxDTOs);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 根据ID获取信箱
    @GetMapping("/{id}")
    public ResponseEntity<?> getMailboxById(@PathVariable Long id) {
        try {
            Optional<Mailbox> mailbox = mailboxService.findById(id);
            if (mailbox.isPresent()) {
                MailboxDTO mailboxDTO = DTOMapper.toMailboxDTO(mailbox.get());
                return ResponseEntity.ok(mailboxDTO);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 创建信箱
    @PostMapping
    public ResponseEntity<?> createMailbox(@RequestBody Mailbox mailbox) {
        try {
            Mailbox savedMailbox = mailboxService.save(mailbox);
            MailboxDTO mailboxDTO = DTOMapper.toMailboxDTO(savedMailbox);
            return ResponseEntity.ok(new ApiResponse(true, "信箱创建成功", mailboxDTO));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 更新信箱
    @PutMapping("/{id}")
    public ResponseEntity<?> updateMailbox(@PathVariable Long id, @RequestBody Mailbox mailboxDetails) {
        try {
            Mailbox updatedMailbox = mailboxService.update(id, mailboxDetails);
            if (updatedMailbox != null) {
                MailboxDTO mailboxDTO = DTOMapper.toMailboxDTO(updatedMailbox);
                return ResponseEntity.ok(new ApiResponse(true, "信箱更新成功", mailboxDTO));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 删除信箱
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteMailbox(@PathVariable Long id) {
        try {
            Optional<Mailbox> mailbox = mailboxService.findById(id);
            if (mailbox.isPresent()) {
                mailboxService.delete(id);
                return ResponseEntity.ok(new ApiResponse(true, "信箱删除成功"));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 批量删除信箱
    @DeleteMapping("/batch")
    public ResponseEntity<?> batchDeleteMailboxes(@RequestBody List<Long> ids) {
        try {
            mailboxService.deleteAll(ids);
            return ResponseEntity.ok(new ApiResponse(true, "信箱批量删除成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 根据业主ID获取信箱
    @GetMapping("/owner/{ownerId}")
    public ResponseEntity<?> getMailboxesByOwner(@PathVariable Long ownerId) {
        try {
            List<Mailbox> mailboxes = mailboxService.findByOwnerId(ownerId);
            List<MailboxDTO> mailboxDTOs = DTOMapper.toMailboxDTOList(mailboxes);
            return ResponseEntity.ok(mailboxDTOs);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 根据状态或类型搜索信箱
    @GetMapping("/search")
    public ResponseEntity<?> searchMailboxes(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type) {
        try {
            List<Mailbox> mailboxes;
            if (status != null && !status.isEmpty()) {
                mailboxes = mailboxService.findByStatus(status);
            } else if (type != null && !type.isEmpty()) {
                mailboxes = mailboxService.findByType(type);
            } else {
                mailboxes = mailboxService.findAll();
            }
            List<MailboxDTO> mailboxDTOs = DTOMapper.toMailboxDTOList(mailboxes);
            return ResponseEntity.ok(mailboxDTOs);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
} 